package com.surfilter.massdata.es.core.client.pool;

import org.apache.commons.pool.impl.StackObjectPool;
import org.apache.log4j.Logger;

import com.surfilter.massdata.es.core.client.EsClient;
import com.surfilter.massdata.es.core.client.EsEnv;

public class EsClientPool {
	
	private String clusterName;

	private String ip;
	
	private String port;
	
	private int keepClienNum;
	
	
	protected static final Logger logger = Logger.getLogger(EsClientPool.class);
	
	private StackObjectPool<EsClient> pool = null;
	
    public EsClientPool(String clusterName, String ip, String port,int keepClienNum) {
		super();
		this.clusterName = clusterName;
		this.ip = ip;
		this.port = port;
		this.keepClienNum = keepClienNum;
		
		EsEnv esEnv = new EsEnv();
    	esEnv.setClusterName(clusterName);
    	esEnv.setIp(ip);
    	esEnv.setPort(port);
    	
    	pool =  new StackObjectPool<EsClient>(new PoolableUserFactory(esEnv), keepClienNum);
	}
    
    public String getClusterName() {
		return clusterName;
	}
	public void setClusterName(String clusterName) {
		this.clusterName = clusterName;
	}
	public String getIp() {
		return ip;
	}
	public void setIp(String ip) {
		this.ip = ip;
	}
	public String getPort() {
		return port;
	}
	public void setPort(String port) {
		this.port = port;
	}
	public int getKeepClienNum() {
		return keepClienNum;
	}
	public void setKeepClienNum(int keepClienNum) {
		this.keepClienNum = keepClienNum;
	}
	public EsClient getEsClient(){
    	EsClient esClient = null;
    	try {
			esClient = pool.borrowObject();
		} catch (Exception e) {
			logger.error("create Client error!" , e);
		}
    	return esClient;
    }
    
    public EsClient removeEsClient(EsClient esClient){
    	try {
			pool.returnObject(esClient);
		} catch (Exception e) {
			logger.error("Client return to pool error!" , e);
		}
    	return esClient;
    }
    
}
